package a10_动态规划;

/**
 * <p>
 * a48_不同的子序列复习2
 * </p>
 *
 * @author flyduck
 * @since 2025/3/25
 */
public class a48_不同的子序列复习2 {
    public static void main(String[] args) {
        System.out.println(numDistinct("babgag", "bag"));
    }
    //dp[i][j]：chars1[0~i-1]种出现chars2[0~j-1]的次数

    //递推公式：
    //if(chars1[i-1] == chars2[j-1]){
    //  dp[i][j] = dp[i-1][j] + dp[i-1][j-1] = 4

    //  dp[i-1][j] = 1
    //  chars1=babga
    //  chars2=   bag
    //
    //  chars1[i-2]的基础上来了一个g，其实我们计算的就是在原来的基础上增加一个g，增加了多少种情况，其实也就是之前有多个种ba即dp[i-1][j-1] = 3
    //  chars1=babgag
    //  chars2=   bag
    //}else{
    //  dp[i][j] = dp[i-1][j];
    //}

    //初始化：
    //来自于左上和上，所以需要初始化第一行和第一列
    //dp[1~chars1.length][0] = 1
    //dp[0][1~chars2.length] = 0
    //dp[0][0] = 1
    public static int numDistinct(String s, String t) {
        char[] chars1 = s.toCharArray();
        char[] chars2 = t.toCharArray();

        int[][] dp = new int[chars1.length+1][chars2.length+1];
        for (int i = 1; i < chars1.length; i++) {
            dp[i][0] = 1;
        }

        for (int j = 1; j < chars2.length; j++) {
            dp[0][j] = 0;
        }

        dp[0][0] = 1;
        for (int i = 1; i <= chars1.length; i++) {
            for (int j = 1; j <= chars2.length; j++) {
                if(chars1[i-1] == chars2[j-1]){
                    dp[i][j] = dp[i-1][j]+dp[i-1][j-1];
                }else {
                    dp[i][j] = dp[i-1][j];
                }
            }
        }

        return dp[chars1.length][chars2.length];
    }
}
